package cn.snsprj.authserver.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author SKH
 * @date 2018-08-20 13:55
 **/
public class CookieUtil {

    private static Logger logger = LoggerFactory.getLogger(CookieUtil.class);

    public static String getCookie(HttpServletRequest request, String cookieName) {

        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(cookieName)) {
                    return cookie.getValue();
                }
            }
        }

        return null;
    }

    public static void writeCookie(HttpServletResponse response, String cookieName, String value) {
        Cookie cookie = new Cookie(cookieName, value);
        cookie.setPath("/");
        cookie.setMaxAge(3600);
        response.addCookie(cookie);
    }

    public static void deleteCookie(HttpServletRequest request, HttpServletResponse response,
            String cookieName) {

        Cookie[] cookies = request.getCookies();
        if (null == cookies) {
            logger.info("====> delete cookie failed, cookie is null, cookieName is {}",cookieName);
        } else {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(cookieName)) {
                    cookie.setValue(null);
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    logger.info("====> delete cookie success, cookieName is {}", cookieName);
                    response.addCookie(cookie);
                    break;
                }
            }
        }
    }


}
